//
//  ZJIssueNewsViewController.m
//  ShangHaiHuDongApp
//
//  Created by ZJ on 2017/7/3.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJIssueNewsViewController.h"
#import "ZJRBTextFliedView.h"
#import "ZJSIPotoView.h"
#import "MyICRemarkView.h"
#import "ZLPhotoActionSheet.h"
#import "ZJIssueNewsModel.h"
#import <AFNetworking.h>
#import "LCustomAlertView.h"
@interface ZJIssueNewsViewController ()<ZJSIPotoViewDelegate,LCustomAlertDelegate>
{
    NSInteger _index;/**< 记录图片数组的长度 */
    NSInteger _seleImageIndex;/**< 上传选择图片的下表，用于对图片进行备注 */
    
    NSInteger _deleImageIndex;/**< 删除图片的下标 */
}
/** scrollview */
@property (nonatomic, strong) UIScrollView *scrollView;
/** 名字 */
@property (nonatomic, strong) ZJRBTextFliedView *name;
/** imageView */
@property (nonatomic, strong) UIImageView *imageView;
/** 照片 */
@property (nonatomic, strong) ZJSIPotoView *potoView;
/** 备注 */
@property (nonatomic, strong) MyICRemarkView *remarkView;
/** 图片数组 */
@property (nonatomic, strong) NSMutableArray *imageArray;

/** 发布 */
@property (nonatomic, strong) UIButton *button;
/** 弹窗视图 */
@property (nonatomic, strong) JCAlertView *deleAlerView;

@end

@implementation ZJIssueNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"发布新闻";
    [self setupUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupUI{
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.name];
    [self.scrollView addSubview:self.imageView];
    [self.scrollView addSubview:self.potoView];
    [self.scrollView addSubview:self.remarkView];
    [self.scrollView addSubview:self.button];
    
    self.name.sd_layout
    .topSpaceToView(self.scrollView, 0)
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .heightIs(self.name.height);
    
    self.imageView.sd_layout
    .topSpaceToView(self.name, 10 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.scrollView, 25 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.scrollView, 25 * [UIScreen zj_screenWScale])
    .heightIs(200 * [UIScreen zj_screenHScale]);
    
    self.potoView.sd_layout
    .topSpaceToView(self.imageView, 0)
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .heightIs(self.potoView.height);
    
    self.remarkView.sd_layout
    .topSpaceToView(self.potoView, 0)
    .leftEqualToView(self.potoView)
    .rightEqualToView(self.potoView)
    .heightIs(self.remarkView.height);
    
    self.button.sd_layout
    .topSpaceToView(self.remarkView, 22 * [UIScreen zj_screenWScale])
    .leftSpaceToView(self.scrollView, 38 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.scrollView, 38 * [UIScreen zj_screenHScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    [self.scrollView setupAutoContentSizeWithBottomView:self.button bottomMargin:30 * [UIScreen zj_screenHScale]];
    
    
}
//键盘将要消失
- (void)keyboardWillDismiss:(NSNotification *)notification {
    if (self.imageArray.count > _seleImageIndex) {
        NetWorkUploadFileModel *model = self.imageArray[_seleImageIndex];
        model.DESC = self.remarkView.textView.text;
        self.imageArray[_seleImageIndex] = model;
    }
}

#pragma mark - LCustomAlertDelegate(谈提示框) 协议方法
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    [self.deleAlerView dismissWithCompletion:nil];
    if (index == 1) {
        [self.imageArray removeObjectAtIndex:_deleImageIndex];
        _index = self.imageArray.count;
        [self.potoView updateUI_PotoArray:self.imageArray];
        
        self.potoView.sd_layout
        .topSpaceToView(self.imageView, 0)
        .leftSpaceToView(self.scrollView, 0)
        .rightSpaceToView(self.scrollView, 0)
        .heightIs(self.potoView.height);
        [self.potoView updateLayout];
        NetWorkUploadFileModel *model = self.imageArray.lastObject;
        if (model) {
            _seleImageIndex = self.imageArray.count - 1;
            self.imageView.image = [UIImage imageWithData:model.FILE_PATH];
            self.imageView.contentMode = UIViewContentModeScaleAspectFit;
            self.remarkView.textView.text = model.DESC;
            
        }else{
            self.imageView.image = PlaceholderBIGImage;
            self.imageView.contentMode = UIViewContentModeScaleAspectFill;
            self.remarkView.textView.text = @"";
            _seleImageIndex = 0;
        }
    }
}
#pragma mark - ZJSIPotoViewDelegate（图片选择模块） 协议方法
- (void)ZJSIPotoViewDelegate_addPotoClick{
    [self.view endEditing:YES];
    _index = self.imageArray.count;
    //图片多选模块
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置最大选择数量
    actionSheet.maxSelectCount = 9;
    //设置预览图最大数目
    actionSheet.maxPreviewCount = 20;
    __weak typeof(self) weakSelf = self;
    [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:nil completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
        
        //修改image的FILE_INDEX
        NSMutableArray *array = [NSMutableArray array];
        [weakSelf.imageArray enumerateObjectsUsingBlock:^(NetWorkUploadFileModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.FILE_INDEX = [NSString stringWithFormat:@"%ld",idx];
            [array addObject:obj];
        }];
        weakSelf.imageArray = array;
        [selectPhotos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData * data = [ToolClass compressionImageWithImage:obj compressionMaxLimit:COMPRESSIONMAXLIMIT];
            NetWorkUploadFileModel *model = [NetWorkUploadFileModel new];
            model.FILE_NAME = [NSDateFormatter stringTimeWithDate:[NSDate date]];
            model.FILE_INDEX = [NSString stringWithFormat:@"%ld",_index  + idx];
            model.FILE_PATH = data;
            model.NAME = @"NEWS_IMG";
            model.DESC = @"";
            [weakSelf.imageArray addObject:model];
        }];
        _index = self.imageArray.count;
        [weakSelf.potoView updateUI_PotoArray:weakSelf.imageArray];
        weakSelf.potoView.sd_layout
        .topSpaceToView(self.imageView, 0)
        .leftSpaceToView(self.scrollView, 0)
        .rightSpaceToView(self.scrollView, 0)
        .heightIs(self.potoView.height);
        [self.potoView updateLayout];
        NetWorkUploadFileModel *model = weakSelf.imageArray.lastObject;
        if (model) {
            _seleImageIndex = self.imageArray.count - 1;
            weakSelf.imageView.image = [UIImage imageWithData:model.FILE_PATH];
            self.imageView.contentMode = UIViewContentModeScaleAspectFit;
            self.remarkView.textView.text = model.DESC;
            
        }else{
            weakSelf.imageView.image = PlaceholderBIGImage;
            self.imageView.contentMode = UIViewContentModeScaleAspectFill;
            self.remarkView.textView.text = @"";
            _seleImageIndex = 0;
        }
    }];
  
}
- (void)ZJSIPotoViewDelegate_potoImageClick_index:(NSInteger)index{
    //对原来的图片赋值
    NetWorkUploadFileModel *oldModel = self.imageArray[_seleImageIndex];
    oldModel.DESC = self.remarkView.textView.text;
    self.imageArray[_seleImageIndex] = oldModel;
    //切换现在的图片
    NetWorkUploadFileModel *model = self.imageArray[index];
    self.imageView.image = [UIImage imageWithData:model.FILE_PATH];
    _seleImageIndex = index;
    self.remarkView.textView.text = model.DESC;
}
- (void)ZJSIPotoViewDelegate_deletePotoClick_index:(NSInteger)index{
    _deleImageIndex = index;

     UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否确定删除图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
     [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         
         [self.imageArray removeObjectAtIndex:_deleImageIndex];
         _index = self.imageArray.count;
         [self.potoView updateUI_PotoArray:self.imageArray];
         
         self.potoView.sd_layout
         .topSpaceToView(self.imageView, 0)
         .leftSpaceToView(self.scrollView, 0)
         .rightSpaceToView(self.scrollView, 0)
         .heightIs(self.potoView.height);
         [self.potoView updateLayout];
         NetWorkUploadFileModel *model = self.imageArray.lastObject;
         if (model) {
             _seleImageIndex = self.imageArray.count - 1;
             self.imageView.image = [UIImage imageWithData:model.FILE_PATH];
             self.imageView.contentMode = UIViewContentModeScaleAspectFit;
             self.remarkView.textView.text = model.DESC;
             
         }else{
             self.imageView.image = PlaceholderBIGImage;
             self.imageView.contentMode = UIViewContentModeScaleAspectFill;
             self.remarkView.textView.text = @"";
             _seleImageIndex = 0;
         }
    }]];
     [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
     [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 点击事件/发布资源
- (void)action_affirmButton{
    if (self.name.textField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入标题" inview:self.view];
        [self.name.textField becomeFirstResponder];
        return;
    }
    if (self.imageArray.count == 0) {
        [YJProgressHUD showSuccess:@"请添加图片" inview:self.view];
        return;
    }
   
    [self netWorkingUpData];
   
}

//发布新闻
- (void)netWorkingUpData{
    ZJIssueNewsModel * model = [ZJIssueNewsModel new];
    model.SYS_ACCOUNTID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID :@"";
    model.SYS_PARTYMEMBERID = ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID : @"";
    model.UPLOAD_FILES = self.imageArray;
    model.TITLE = self.name.textField.text;
    model.UNITID = ZJUSERINFORMODEL.DEPT_MODEL_BOOK.ID ? ZJUSERINFORMODEL.DEPT_MODEL_BOOK.ID : @"";
    model.UNIT_NAME = ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.DEPT_NAME;
    model.USERID =  ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID;
    model.USER_NAME = ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME;
    model.ACT_ID = self.ID;
    model.MODE = @"2";
    model.AUTHOR = ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ORGCONCENTER_NAME;
    [self senderNetWorkingModel:model];
}

//网络请求
- (void)senderNetWorkingModel:(NetWorkUpLoadModel *)parameter{
    [YJProgressHUD showMessage:@"发布中..." duration:10 view:self.view];
    __weak typeof(self) weakSelf = self;
    ZJIssueNewsModel *parameter1 = (ZJIssueNewsModel *)parameter;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
    
    //1、把文件对象数组转化成数组
    NSArray *fileArray = [parameter1.UPLOAD_FILES yy_modelToJSONObject];
    //2、除去data，得到数组
    __block NSMutableArray *nofileDataArray = [NSMutableArray array];//保存新数组
    
    NSDictionary *netWorkUpLoadModel = [parameter1 yy_modelToJSONObject];
    
    [fileArray enumerateObjectsUsingBlock:^(NSMutableDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeObjectForKey:@"fileUrl"];
        [nofileDataArray addObject:obj];
    }];
    
    
    NSString * dateString = [NSString stringWithFormat:@"FILES_%@_KEYS",[NSString getCurrentDate]];
    
    [manager POST:UPLOADURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [netWorkUpLoadModel.allKeys enumerateObjectsUsingBlock:^(NSString *  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            //不为fileArray 且有值时
            if (![key isEqualToString:@"UPLOAD_FILES"] && [netWorkUpLoadModel objectForKey:key] && ![key isEqualToString:@"frequency"]) {
                [formData appendPartWithFormData:[netWorkUpLoadModel[key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
            }
        }];
        
        [parameter1.UPLOAD_FILES enumerateObjectsUsingBlock:^(NetWorkUploadFileModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.FILE_PATH) {
                NSData  *fileData= obj.FILE_PATH;//二进制数据
                NSString *mimeType= @"image/jpeg";//文件类型
                //                NSString *oldFileNameLast=[obj.FILE_NAME lastPathComponent];//文件原来的名字
                //取文件名的后缀
                //                NSString *fileNameLast = [oldFileNameLast zj_subStringLastOfString:@"."];
                //拼接最新的文件名
                NSString *fileName = [NSString stringWithFormat:@"%ld%@",(unsigned long)idx,@".jpg"];
                [formData appendPartWithFileData:fileData name: obj.NAME fileName:fileName mimeType:mimeType];
            }
        }];
        
        [formData appendPartWithFormData:[nofileDataArray yy_modelToJSONData] name:dateString];
        [formData appendPartWithFormData:[@"news.action.CreateNews" dataUsingEncoding:NSUTF8StringEncoding] name:@"ACTION_XML"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:responseObject];
        if ([model.STATE isEqualToString:@"20000"]) {
            [YJProgressHUD showSuccess:@"发布成功" inview:weakSelf.view];
            if (weakSelf.block) {
                weakSelf.block();
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [YJProgressHUD showSuccess:@"发布失败" inview:weakSelf.view];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        [YJProgressHUD showSuccess:@"发布失败" inview:weakSelf.view];
    }];
}



#pragma mark - Getter
- (UIScrollView *)scrollView{
    if (_scrollView == nil){
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight)];
    }
    return _scrollView;
}
- (UIImageView *)imageView{
    if (_imageView == nil){
        _imageView = [UIImageView new];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.image = PlaceholderBIGImage;
        _imageView.clipsToBounds  = YES;
    }
    return _imageView;
}

- (ZJRBTextFliedView *)name{
    if (_name == nil){
        _name = [[ZJRBTextFliedView alloc] initWithFrame:CGRectMake(0, LP_TopHeight + 20 * [UIScreen zj_screenWScale], self.view.width, 90 * [UIScreen zj_screenHScale]) title:@"标题 :"];
        _name.maxNumber = 50;
        [self setViewUpdate:_name];
    }
    return _name;
}
- (void)setViewUpdate:(ZJRBTextFliedView *)viewUpdate{
    viewUpdate.titleLabel.frame = CGRectMake(12 * [UIScreen zj_screenWScale], viewUpdate.titleLabel.y, self.view.width - 24 * [UIScreen zj_screenWScale], viewUpdate.titleLabel.height);
    viewUpdate.textField.frame = CGRectMake(12 * [UIScreen zj_screenWScale], viewUpdate.textField.y, self.view.width - 24 * [UIScreen zj_screenWScale], viewUpdate.textField.height);
}

- (ZJSIPotoView *)potoView{
    if (_potoView == nil){
        _potoView = [[ZJSIPotoView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 195  * [UIScreen zj_screenHScale]) title:@"照片 :"];
        [_potoView updateUI_PotoArray:nil];
        _potoView.deletate = self;
    }
    return _potoView;
}
- (MyICRemarkView *)remarkView{
    if (_remarkView == nil){
        _remarkView = [[MyICRemarkView alloc]initWithFrame:CGRectMake(0, 64 + 20 * [UIScreen zj_screenHScale], self.view.width, 195 * [UIScreen zj_screenHScale]) title:@"图片备注 :"];
        _remarkView.maxNumber = 200;
    }
    return _remarkView;
}
- (UIButton *)button{
    if (_button == nil){
        _button = [UIButton new];
        [_button setTitle:@"确认发布" forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _button.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        _button.titleLabel.font = [UIFont titleTextFont];
        _button.backgroundColor = [UIColor themeColor];
        [_button addTarget:self action:@selector(action_affirmButton) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _button;
}
- (NSMutableArray *)imageArray{
    if (_imageArray == nil){
        _imageArray = [NSMutableArray array];
        
    }
    return _imageArray;
}
- (JCAlertView *)deleAlerView{
    if (_deleAlerView == nil){
        LCustomAlertView *view = [[LCustomAlertView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight]) alertMessage:@"是否删除图片" titlesArray:@[@"取消",@"确认"]];
        view.delegate = self;
        _deleAlerView = [[JCAlertView alloc] initWithCustomView:view dismissWhenTouchedBackground:YES];
    }
    return _deleAlerView;
}
@end
